package com.bdy.lm.browser.servlet;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * 
 * @author liming
 * 需要对响应编码进行处理
 * 将参数和值读取并保存到Map类型的form中
 * 
 * 接受表单，并检查是否为文件上传
 */

public class BaseFileServlet extends HttpServlet {

	public Map<String, Object> form = new HashMap<String, Object>();
	public String fileName;

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String methodName = null;
		try {
			//创建一个DiskFileItemFactory工厂
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			//判断提交上来的数据是否是上传表单的数据
			if (ServletFileUpload.isMultipartContent(request)) {
				//使用ServletFileUpload解析器解析上传数据，解析结果返回的是一个List<FileItem>集合，每一个FileItem对应一个Form表单的输入项
				List<FileItem> list = upload.parseRequest(request);
				for(FileItem item : list) {
					if (item.isFormField()) {
						form.put(item.getFieldName(), item.getString("UTF-8"));
					} else {
						byte[] byt = new byte[item.getInputStream().available()];
						item.getInputStream().read(byt);
						form.put(item.getFieldName(), byt);
						fileName = item.getFieldName();
					}
				}
				methodName = (String) form.get("method");
				//System.out.println(form.toString());
			} else {
				methodName = request.getParameter("method");
				//System.out.println("other:" + methodName);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		/**
		 * 1. 获取method参数，它是用户想调用的方法 2. 把方法名称变成Method类的实例对象 3. 通过invoke()来调用这个方法
		 * 
		 */
		try {
			if (methodName != null) {
				Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
				method.invoke(this, request, response);
			}
		} catch (NoSuchMethodException e1) {
			throw new RuntimeException("您要调用的方法：" + methodName + "不存在！", e1);
		} catch (IllegalArgumentException e2) {
			throw new RuntimeException(e2);
		} catch (IllegalAccessException e3) {
			throw new RuntimeException(e3);
		} catch (InvocationTargetException e4) {
			throw new RuntimeException(e4);
		}
	}
}
